import os

import pandas as pd
import tushare as ts
from loguru import logger

from models.global_config import glm
from models.stock_model import StockNumber, DayInfo


def get_all_stock(fw, N, stocks, end_date):
    df = pd.read_csv('all.csv')
    count = 0
    for row in df.index:
        if stocks and df.loc[row]['ts_code'] not in stocks:
            continue
        sn = StockNumber(df.loc[row])
        if '退' in sn.name:
            continue
        if 'ST' in sn.name:
            continue
        if not str(sn.ts_code).startswith('60') \
                and not str(sn.ts_code).startswith('00'):
            continue
        count += 1
        analysis_stock(fw, N, sn, end_date)


def analysis_stock(fw, N, sn, end_date):
    csv_path = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(csv_path):
        pro = ts.pro_api(token='bbc6f076aa3d2b063cb26376ad12ffd94b53864b42d2344b3aa2039f')
        df2 = pro.daily(ts_code=sn.ts_code)
        save_dir = f'../../stocks'
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        df2.to_csv(csv_path)
        print(f'save {sn.ts_code} {sn.name} 成功')
    df2 = pd.read_csv(csv_path)
    q10 = []
    all_di = []
    today_di = None
    before_day_di = None
    for row2 in df2.index:
        di = DayInfo(sn, df2.loc[row2])
        di.name = sn.name
        di.ts_code = sn.ts_code
        di.industry = sn.industry
        # di.trade_date = df2.loc[row2]['trade_date']
        if str(di.trade_date) > str(end_date):
            continue
        # di.open = df2.loc[row2]['open']
        # di.high = df2.loc[row2]['high']
        # di.low = df2.loc[row2]['low']
        # di.close = float(df2.loc[row2]['close'])
        if today_di and di.low > today_di.high:
            break
        if di.close < glm.min_price:
            break
        # di.pre_close = df2.loc[row2]['pre_close']
        # di.change = df2.loc[row2]['change']
        # di.pct_chg = float(df2.loc[row2]['pct_chg'])
        # di.vol = df2.loc[row2]['vol']
        # di.amount = df2.loc[row2]['amount']
        if len(q10) == N * 2 + 1:
            if max(q10) == q10[N]:
                top_di = all_di[N]
                link_code_arr = sn.ts_code.split('.')
                link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
                hyperlink = f'{di.name},= HYPERLINK("https://xueqiu.com/S/{link_code}")'
                msg = f'{today_di.trade_date},{top_di.trade_date},{top_di.high},{before_day_di.low},{today_di.industry},{hyperlink}\n'
                fw.write(msg)
                break
            else:
                all_di.pop(0)
                q10.pop(0)
        all_di.append(di)
        q10.append(di.high)
        if today_di and before_day_di is None:
            before_day_di = di
        if today_di is None:
            today_di = di


def printNumber(file_path, N, end_date, stocks):
    with open(file_path, 'a+') as fw:
        for stock in stocks:
            get_all_stock(fw, N, stock, end_date)


def run(stocks, bkd=200, N=10):
    log_dir = 'result'
    file_name = 'eq3_top_{}.csv'.format(N)
    file_path = f'{log_dir}/{file_name}'
    with open(file_path, 'w') as fw:
        title = "today_date,top_date,top_v,bv,行业,名字,超链接\n"
        fw.write(title)
    for idx, trade_date in enumerate(glm.all_trade_date_arr):
        if idx > bkd:
            break
        printNumber(file_path, N, trade_date, stocks)
    logger.info(f'{file_path}生成完成')
